<template>
  <div class="building-container">
    <!-- 搜索区域 -->
    <div class="search-container">
      <div class="search-label">企业名称：</div>

      <el-input
        v-model="params.name"
        clearable
        placeholder="请输入内容"
        class="search-main"
      />
      <el-button type="primary" @click="doSearch">查询</el-button>
    </div>

    <div class="create-container">
      <el-button type="primary" @click="$router.push('/enterpriseAdd')"
       v-auth-btn="'park:enterprise:add_edit'"
        >添加企业</el-button
      >
    </div>

    <!-- 表格区域 -->
    <div class="table">
      <el-table
        style="width: 100%"
        :data="enterPriseList"
        @expand-change="handleExpandChange"
      >
        <!-- 序号的前面,展开行   -->
        <el-table-column type="expand">
          <template #default="{ row }">
            <el-table :data="row.rentList">
              <el-table-column
                label="租赁楼宇"
                width="320"
                prop="buildingName"
              />
              <el-table-column label="租赁起始时间" prop="startTime" />
              <el-table-column label="合同状态" prop="status">
                <template slot-scope="scope">
                  <el-tag>{{ mapStatus[scope.row.status] }} </el-tag>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="180">
                <template #default="scope">
                  <el-button
                    size="mini"
                    type="text"
                    :disabled="scope.row.status === 3"
                    @click="outRent(scope.row.id)"
                    v-auth-btn="'park:rent:add_surrender'"
                    >退租</el-button
                  >
                  <el-button
                    size="mini"
                    type="text"
                    :disabled="scope.row.status !== 3"
                    @click="deleteRent(scope.row.id)"
                    v-auth-btn="'park:rent:remove'"
                    >删除</el-button
                  >
                </template>
              </el-table-column>
            </el-table>
          </template>
        </el-table-column>

        <el-table-column type="index" label="序号" />
        <el-table-column label="企业名称" width="320" prop="name" />
        <el-table-column label="联系人" prop="contact" />
        <el-table-column label="联系电话" prop="contactNumber" />
        <el-table-column label="操作">
          <!-- 操作按钮 -->
          <template #default="scope">
            <el-button size="mini" type="text" @click="addRent(scope.row)"
            v-auth-btn="'park:rent:add_surrender'"
              >添加合同</el-button
            >

            <el-button
              size="mini"
              type="text"
              @click="showEnterprise(scope.row.id)"
              v-auth-btn="'park:enterprise:query'"
              >查看</el-button
            >

            <el-button
              size="mini"
              type="text"
              @click="editEnterprise(scope.row.id)"
              v-auth-btn="'park:enterprise:add_edit'"
              >编辑</el-button
            >

            <el-button
              size="mini"
              type="text"
              @click="deleteEnterprise(scope.row.id)"
              v-auth-btn="'park:enterprise:remove'"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </div>

    <div class="page-container">
      <el-pagination
        layout="total, prev, pager, next"
        :total="total"
        :page-size="params.pageSize"
        @current-change="pageChange"
      />
    </div>
    <!-- 添加合同详情对话框 -->
    <el-dialog
      title="添加合同"
      :visible="rentDialogVisible"
      width="580px"
      @close="closeDialog"
    >
      <!-- 表单区域 -->
      <div class="form-container">
        <el-form
          ref="addForm"
          :model="rentForm"
          :rules="rentRules"
          label-position="top"
        >
          <el-form-item label="租赁楼宇" prop="buildingId">
            <el-select v-model="rentForm.buildingId" placeholder="请选择">
              <el-option
                v-for="item in buildList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="租赁起止日期" prop="rentTime">
            <el-date-picker
              v-model="rentForm.rentTime"
              type="daterange"
              range-separator="-"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="yyyy-MM-dd"
            />
          </el-form-item>

          <el-form-item label="租赁合同" prop="contractId">
            <el-upload action="#" :http-request="uploadFile">
              <el-button size="small" type="primary" plain
                >上传合同文件</el-button
              >

              <div slot="tip" class="el-upload__tip">
                支持扩展名：.doc .docx .pdf, 文件大小不超过5M
              </div>
            </el-upload>
          </el-form-item>
        </el-form>
      </div>

      <template #footer>
        <el-button size="mini" @click="closeDialog">取 消</el-button>

        <el-button size="mini" type="primary" @click="submitRentForm"
          >确 定</el-button
        >
      </template>
    </el-dialog>
  </div>
</template>
<script>
import {
  getEnterpriseListAPI,
  getRentListAPI,
  getRentBuildListAPI,
  uploadFileAPI,
  createRentAPI,
  deleteEnterpriseAPI,
  outRentAPI,
  deleteRentAPI,
} from "@/api/enterprise";
export default {
  name: "Building",
  data() {
    return {
      enterPriseList: [], //企业列表
      params: {
        page: 1,
        pageSize: 5,
        name: "", // 增加字段name
      },
      // rentList: [], //合同列表
      total: 0, //总条数
      mapStatus: {
        0: "待生效",
        1: "生效中",
        2: "已到期",
        3: "已退租",
      }, //合同状态
      rentDialogVisible: false,
      //添加合同相关数据
      rentForm: {
        buildingId: null, // 楼宇id
        contractId: null, // 合同id
        contractUrl: "", // 合同Url
        enterpriseId: null, // 企业名称
        type: 0, // 合同类型
        rentTime: [], // 合同时间
      },
      rentRules: {
        buildingId: [
          { required: true, message: "请选择楼宇", trigger: "change" },
        ],
        rentTime: [
          { required: true, message: "请选择租赁日期", trigger: "change" },
        ],
        contractId: [{ required: true, message: "请上传合同文件" }],
      },
      buildList: [], //楼宇列表
    };
  },
  mounted() {
    this.getExterpriseList();
  },
  methods: {
    //删除合同
    deleteRent(id){
      this.$confirm("此操作将永久删除该合同信息, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          try {
            await deleteRentAPI(id);
            this.getExterpriseList();
            this.$message({
              type: "success",
             message: "删除成功!",
            })
          }catch(error) {
            console.error(error);
          
          }
        })

    },
    //退租
    outRent(rentId) {
      this.$confirm("确认退租吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          try {
            await outRentAPI(rentId);
            this.getExterpriseList();
            this.$message({
              type: "success",
              message: "退租成功!",
            });
          } catch (error) {
            
          }
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    //查看企业
    showEnterprise(id) {
      this.$router.push({ path: "/enterpriseDetail", query: { id } });
    },
    //删除企业
    deleteEnterprise(id) {
      this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(async () => {
        await deleteEnterpriseAPI(id).then((res) => {
          this.$message({
            type: "success",
            message: "删除成功!",
          });
          this.getExterpriseList();
        });
      });
    },
    //跳转编辑
    editEnterprise(id) {
      // console.log(row);

      this.$router.push({ path: "/enterpriseEdit", query: { id } });
    },
    //确认提交
    async submitRentForm() {
      //1.完成表单验证
      try {
        await this.$refs.addForm.validate();
        //2.搜集请求数据
        let data = {
          buildingId: this.rentForm.buildingId,
          enterpriseId: this.rentForm.enterpriseId,
          startTime: this.rentForm.rentTime[0],
          endTime: this.rentForm.rentTime[1],
          contractId: this.rentForm.contractId,
          contractUrl: this.rentForm.contractUrl,
          type: 0,
        };
        //3.发送请求
        await createRentAPI(data).then((res) => {
          // console.log(res);
          this.$message.success("添加合同成功");
        });
        //4.关闭弹框
        this.rentDialogVisible = false;
      } catch (err) {
        console.log(err);
      }
    },
    //上传合同
    async uploadFile(fileData) {
      const { file } = fileData;
      const formData = new FormData();
      formData.append("file", file);
      formData.append("type", "contract");
      const res = await uploadFileAPI(formData);
      const { id, url } = res.data;
      this.rentForm.contractId = id;
      this.rentForm.contractUrl = url;
      // console.log(res);
      // 单独校验表单
      this.$refs.addForm.validate("contractId");

      // this.rentForm.contractUrl = res.data;
    },
    // 打开添加合同弹框
    async addRent(row) {
      this.rentForm.enterpriseId = row.id;
      this.rentDialogVisible = true;

      // 获取楼宇下拉列表
      const res = await getRentBuildListAPI();
      this.buildList = res.data;
      // console.log(this.buildList);
    },
    // 关闭添加合同弹窗
    closeDialog() {
      this.rentDialogVisible = false;
    },

    //查询企业列表
    doSearch() {
      this.params.page = 1;
      this.getExterpriseList();
    },
    //获取企业列表
    async getExterpriseList() {
      const res = await getEnterpriseListAPI(this.params);
      const obj = res.data.rows;
      const enterPriseList = obj.map((item) => {
        return {
          ...item,
          rentList: [],
        };
      });
      this.enterPriseList = enterPriseList;
      this.total = res.data.total;
    },
    //点击页面分页
    pageChange(page) {
      // 更改参数
      this.params.page = page;
      // 重新获取数据渲染
      this.getExterpriseList();
    },
    //处理展开企业的租赁信息列表
    async handleExpandChange(row, rows) {
      // console.log(row, rows);
      // 获取企业id,发送请求
      //做一个展开和收起的判断
      let index = rows.findIndex((item) => item.id === row.id);
      if (index > -1) {
        const res = await getRentListAPI(row.id);
        // console.log(res.data);
        row.rentList = res.data;
      }
    },
  },
};
</script>


<style lang="scss" scoped>
.department-container {
  padding: 10px;
}

.search-container {
  display: flex;
  align-items: center;
  border-bottom: 1px solid rgb(237, 237, 237, 0.9);
  padding-bottom: 20px;

  .search-label {
    width: 100px;
  }

  .search-main {
    width: 220px;
    margin-right: 10px;
  }
}
.create-container {
  margin: 10px 0px;
}
.page-container {
  padding: 4px 0px;
  text-align: right;
}
.form-container {
  padding: 0px 80px;
}
</style>
